<?php
header('Cache-Control: no-cache, must-revalidate');
//header('Content-type: application/json');


/**
 * @see Zend_Loader
 */
require_once '../../lib/gdata/Zend/Loader.php';

Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata_Photos');
Zend_Loader::loadClass('Zend_Gdata_Photos_UserQuery');
Zend_Loader::loadClass('Zend_Gdata_Photos_AlbumQuery');
Zend_Loader::loadClass('Zend_Gdata_Photos_PhotoQuery');
Zend_Loader::loadClass('Zend_Gdata_App_Extension_Category');

class GWTGalleria {

/*
* 	define google account
*/
const User = "";
const Pass = "";

const Mysql_User = "";
const Mysql_Pass = "";
const Mysql_DB = "";
const Mysql_table_album = "";
const Mysql_table_photo = "";

/* 
* do not change
*/
var $photo;
var $description;

function GWTGalleria() {

	if($_GET['get'] == 'album' && $_GET['albumid']) {
		$this->connectToPicasa();
		$this->getAlbum($_GET['albumid']);
	}
	
}

function connectToPicasa() {
	$svc = Zend_Gdata_Photos::AUTH_SERVICE_NAME;

	$client = Zend_Gdata_ClientLogin::getHttpClient(GWTGalleria::User, GWTGalleria::Pass, $svc);
	$photo = new Zend_Gdata_Photos($client);
	
	$this->photo = $photo;
}

function connectToMysql() {
	mysql_connect("localhost", GWTGalleria::Mysql_User, GWTGalleria::Mysql_Pass);
	mysql_select_db(GWTGalleria::Mysql_DB);
}

function getAlbum($albumId) {
	$query = new Zend_Gdata_Photos_AlbumQuery();
	$query->setUser(GWTGalleria::User);
	$query->setAlbumId($albumId);
	$query->setThumbsize('104c');
	$query->setImgMax('1280');
	
	//echo $query->getQueryUrl();
	$albumFeed = $this->photo->getAlbumFeed($query);

	/*
	* load descriptions
	*/
	$this->getDescriptions($albumId);
	
	$JSONRespone = array();
	$i = 0;
	
	foreach ($albumFeed as $entry) {
        if ($entry instanceof Zend_Gdata_Photos_PhotoEntry) { 
        	$i++;
        	
        	$thumb = $entry->getMediaGroup()->getThumbnail();
        	$fullsize = $entry->getMediaGroup()->getContent();

        	$object = array('id' => ''.$entry->getGphotoId().'',
        					'thumbnail' => $thumb[0]->getUrl(),
        					'fullsize' => $fullsize[0]->getUrl(),
        					);
        					
        	$desc = $this->getDescriptions($entry->getGphotoId()); 
			if($desc['de'] != null) {
        		$object['desc_de'] = $desc['de'];
        	} else {
        		$object['desc_de'] = '';
        	}
        	if($desc['en'] != null) {
        		$object['desc_en'] = $desc['en'];
        	} else {
        		$object['desc_en'] = '';
        	}
        	
        	$JSONResponse[$i] = $object;
	    }
	}
	
	echo json_encode($JSONResponse);
}

function getDescriptions($photoId) {
	$this->connectToMysql();
	$query = "SELECT de, en FROM ".GWTGalleria::Mysql_table_photo." WHERE photoid='".$photoId."' ";
	$result = mysql_query($query);

	if(mysql_num_rows($result) > 0)
		return mysql_fetch_array($result);
	else 
		return null;
}

}

$Galleria = new GWTGalleria();

?>